<template>
  <div class="upload-file" :class="[size]">
    <el-upload
      :class="['upload-file-uploader', (overLimit || (disabled && disabledHideUpload)) ? 'hide-upload-btn' :'']"
      :multiple="limit !== 1"
      :action="uploadFileUrl"
      :data="extraData"
      :headers="headers"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :on-success="handleUploadSuccess"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :list-type="listType"
      ref="uploadRef"
    >

      <!-- 上传按钮 -->
      <template v-if="listType !== 'picture-card'">
        <el-button size="small" type="primary"  :disabled="disabled">{{ button ? button : '上传'+fileTypeName }}</el-button>
      </template>
      <template v-else>
        <i class="el-icon-plus"></i>
      </template>

      <!-- 上传提示 -->
      <div class="el-upload__tip" slot="tip" v-if="showTip">
        请上传
		    <template v-if="min > 0 && limit > 0">
          <template v-if="min === limit"> <b style="color: #f56c6c">{{ limit }}</b>个</template>
          <template v-else> <b style="color: #f56c6c">{{ min }}-{{ limit }}</b>个</template>
        </template>
        <template v-else-if="min > 0"> 至少<b style="color: #f56c6c">{{min}}</b>个</template>
        <template v-else-if="limit > 0"> 最多<b style="color: #f56c6c">{{limit}}</b>个</template>
        <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
        <template v-if="fileTypeList"> 格式为 <b style="color: #f56c6c">{{ fileTypeList.join("/") }}</b> </template>
        的{{ fileTypeName }}
      </div>

      <template slot="file" slot-scope="{ file }">
        <file-item
          :file="file"
          :size="size"
          :disabled="disabled"
          :progress-type="listType === 'text' ? 'line': 'circle' "
          @remove="removeClick"
        />
      </template>
    </el-upload>
  </div>
</template>

<script>
import FileItem from './FileItem'
import { getToken } from "@/utils/user"
import { UPLOADER, RESPONSE } from '@/config'
import { getFileName, getFileExt } from '@/utils/tools/url'
import { staticUrl } from '@/utils/frame'

export default {
  name: "FileUpload",
  components: { FileItem },
  props: {
    defaultList: [String, Array], // 默认列表
    value: [String, Array],  // 同步值
    uploading: Boolean, // 是否上传中
    resultArray: Boolean, // value的值是否是数组
    disabled: Boolean, // 是否禁用状态
    disabledHideUpload: Boolean, // 禁用状态是否隐藏上传按钮
    size: String, // 展示大小 small 或 空
    button: String, // 上传按钮名称
    overHideUpload: Boolean, // 上传超过数量是否隐藏上传按钮
    extraData: Object, // 上传额外操作
    limit: { // 数量限制
      type: Number,
      default: 5
    },
    min: {  // 最少数量
      type: Number,
        default: 0
    },
    fileSize: { // 大小限制(MB)
      type: Number,
      default: 10
    },
    fileType: {  // 文件后缀类型
      type: Array,
      default: () => []
    },
    isShowTip: { // 是否显示提示
      type: Boolean,
      default: true
    },
    listType: { // 上传列表类型，picture-card | picture | text
      type: String,
      default: 'picture',
    },
    uploadType: { // 上传类型，调用不同接口
      type: String,
      default: 'file'
    },
  },
  data() {
    return {
      uploadList: [], //实际的上传列表
      fileList: [], // 出示给element组件的例表
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  watch: {
    defaultList: {
      handler(val) {
        if (val) {
          // 首先将值转为数组
          const list = Array.isArray(val) ? val : val.split(',')
          // 然后将数组转为对象数组
          let temp = 1
          this.fileList = list.map(item => {
            if (typeof item === 'string') item = { name: getFileName(item), path: item }
            item.url = staticUrl(item.path)
            item.uid = item.uid || new Date().getTime() + temp++
            return item
          })
        } else {
          this.fileList = []
        }
        this.uploadList = JSON.parse(JSON.stringify(this.fileList))
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize)
    },
    // 计算是否超过限制
    overLimit() {
      if (this.limit < 1 || !this.overHideUpload) return false
      return this.uploadList.length >= this.limit
    },
    // 计算上传类型，获取上传接口
    uploadFileUrl(){
      if (this.uploadType === 'image') return UPLOADER.IMAGE
      if (this.uploadType === 'video') return UPLOADER.VIDEO
      return UPLOADER.FILE
    },
    // 计算获取文件类型名称
    fileTypeName(){
      if (this.uploadType === 'image') return '图片'
      if (this.uploadType === 'video') return '视频'
      return '文件'
    },
    // 计算获取上传文件类型后缀限制
    fileTypeList() {
      if (this.fileType && this.fileType.length) {
        if (this.fileType[0] === '*') return []
        return this.fileType
      }
      if (this.uploadType === 'image') return ['png', 'jpg', 'jpeg', 'gif']
      if (this.uploadType === 'video') return ['mp4']
      return ['png', 'jpg', 'jpeg', 'gif', 'pdf', 'txt', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'zip', 'mp4', 'psd']
    }
  },
  methods: {
    // 文件个数超出，
    handleExceed() {
      this.$modal.msgError(`上传${this.fileTypeName}数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError(_, file ) {
      this.$modal.msgError((file?.name || this.fileTypeName) + " 上传失败")
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      if (this.disabled) {
        this.$modal.msgError('当前不支持上传操作')
        return false
      }
      if (this.fileTypeList.length) {  // 校检文件类型
        const fileExt = getFileExt(file.name, true)
        if (!this.fileTypeList.includes(fileExt)) {
          this.$modal.msgError(`${this.fileTypeName}格式不正确, 请上传${this.fileTypeList.join('/')}格式文件!`)
          return false
        }
      }
      if (file.name.includes(',')) { // 校检文件名是否包含特殊字符
        this.$modal.msgError('文件名不正确，不能包含英文逗号!')
        return false
      }
      if (this.fileSize) {  // 校检文件大小
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$modal.msgError(`上传${this.fileTypeName}大小不能超过 ${this.fileSize} MB!`)
          return false
        }
      }
      return true
    },
    // 监听 文件新增、成功、失败
    handleChange(_, fileList){
      const uploading = fileList.some(item =>{
        return item.status !== 'success' && item.status !== 'fail'
      })
      this.uploadList = fileList

      let okList = []
      fileList.map(item => {
        if (item.status === 'success') okList.push({ name: item.name, path: item.path })
      })
      this.$emit('update:uploading', uploading)
      this.emitValue(okList)
    },
    // 监听文件删除
    handleRemove(file, fileList){
      this.handleChange(file, fileList)
    },
    // 自定义删除文件
    removeClick(file) {
      this.$refs.uploadRef.handleRemove(file)
    },
    // 上传结束处理
    handleUploadSuccess(res, file) {
      if (res.code === RESPONSE.SUCCESS_CODE) {
        file.url = res.data.url
        file.path = res.data.path
      } else {
        this.$modal.msgError(file.name + (res?.msg || '上传失败'))
        this.removeClick(file)
      }
    },
    emitValue(fileList) {
      if (this.resultArray) {
        const result = fileList.map(item => {
          return { name: item.name, path: item.path }
        })
        this.$emit('input', result)
      } else {
        this.$emit('input', this.listToString(fileList))
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let result = ''
      separator = separator || ','
      list.map(item => {
        if (item.path) result += item.path + separator
      })
      return result ? result.slice(result, result.length - 1) : ''
    }
  }
};
</script>

<style scoped lang="scss">
.upload-file ::v-deep .el-upload-list__item {
  transition: none !important;
  border: none;
}
::v-deep .el-upload__tip {
  line-height: 1.3;
}
::v-deep .el-upload-list--picture {
  margin: 10px 0 0 0;
  display: block;
  vertical-align: top;
  overflow: hidden;
}
::v-deep .el-upload-list--picture .el-upload-list__item {
  overflow: hidden;
  background-color: #fff;
  box-sizing: border-box;
  width: 120px;
  height: 120px;
  margin: 0 8px 8px 0;
  display: inline-block;
  padding: 0;
}

::v-deep .hide-upload-btn .el-upload{
  display: none;
}

::v-deep .el-upload-list--picture .el-progress.el-progress--circle {
  top: 0;
}

.small {
  ::v-deep .el-upload-list .el-upload-list__item, ::v-deep .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
  ::v-deep .el-upload-list.el-upload-list--text .el-upload-list__item{
    width: 100%;
    height: 80px;
  }
}
</style>
